
const mongoose = require('mongoose');
const _ = require('lodash');
var userService = require('../service/user.service');
const winston = require('winston');

module.exports={
    login:login,
    signOut:signOut
};

/**
 * sign out
 * @param req
 * @param res
 * @param next
 */
function signOut(req,res,next){
    winston.info('User sign out the system');
    req.session.user = null;
    res.json({result:true,data:{}});
}

/**
 * login
 * @param req
 * @param res
 * @param next
 */
function login(req,res,next){
    winston.info('User login the system');
    var body = req.body;
    if(_.isEmpty(body)){
        next(new Error('user body can not be empty'));
    }else {
        userService.findByUserName(body.username,function(err,data){
            if(err){
                res.json({result:false,errMsg:'login fail!'})
            }else {
                if(!data){
                    res.json({result:false,errMsg:'username not existed'});
                }else{
                    if(data.password!=body.password){
                        res.json({result:false,errMsg:'password error'})
                    }else {
                        req.session.user = data;
                        res.json({result:true,data:data});
                    }
                }
            }
        });
    }
}



